package main

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// 简化的加密密钥
const secretKey = "3cb64895b99444ca935a0b3db8307b58"

// 简化的加密工具结构
type CryptoUtil struct {
	key []byte
}

// 创建加密工具实例
func NewCryptoUtil(key string) *CryptoUtil {
	// 直接使用前32字节作为密钥
	keyBytes := make([]byte, 32)
	keyString := []byte(key)
	for i := 0; i < 32; i++ {
		keyBytes[i] = keyString[i%len(keyString)]
	}
	return &CryptoUtil{
		key: keyBytes,
	}
}

// 简化的加密方法（XOR + Base64）
func (c *CryptoUtil) Encrypt(plaintext string) (string, error) {
	plaintextBytes := []byte(plaintext)
	
	// 生成随机IV
	iv := make([]byte, 16)
	if _, err := rand.Read(iv); err != nil {
		return "", err
	}
	
	// 简单的XOR加密
	encryptedBytes := make([]byte, len(plaintextBytes))
	for i := 0; i < len(plaintextBytes); i++ {
		encryptedBytes[i] = plaintextBytes[i] ^ c.key[i%len(c.key)] ^ iv[i%len(iv)]
	}
	
	// 组合IV和密文
	combinedBytes := make([]byte, 16+len(encryptedBytes))
	copy(combinedBytes[:16], iv)
	copy(combinedBytes[16:], encryptedBytes)
	
	return base64.StdEncoding.EncodeToString(combinedBytes), nil
}

// 简化的解密方法
func (c *CryptoUtil) Decrypt(ciphertext string) (string, error) {
	combinedBytes, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}
	
	if len(combinedBytes) < 16 {
		return "", fmt.Errorf("invalid ciphertext length")
	}
	
	iv := combinedBytes[:16]
	encryptedBytes := combinedBytes[16:]
	
	// 简单的XOR解密
	decryptedBytes := make([]byte, len(encryptedBytes))
	for i := 0; i < len(encryptedBytes); i++ {
		decryptedBytes[i] = encryptedBytes[i] ^ c.key[i%len(c.key)] ^ iv[i%len(iv)]
	}
	
	return string(decryptedBytes), nil
}

// 请求和响应结构
type EncryptedRequest struct {
	Data string `json:"data"`
}

type EncryptedResponse struct {
	Success bool   `json:"success"`
	Data    string `json:"data"`
	Message string `json:"message"`
}

type UserData struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	Age      int    `json:"age"`
	Phone    string `json:"phone"`
}

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type LoginResponse struct {
	Token  string `json:"token"`
	UserID int    `json:"user_id"`
	Name   string `json:"name"`
}

// 全局加密工具
var crypto *CryptoUtil

// 中间件：解密请求数据
func DecryptMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == "POST" || c.Request.Method == "PUT" {
			var encReq EncryptedRequest
			if err := c.ShouldBindJSON(&encReq); err != nil {
				fmt.Printf("❌ JSON binding error: %v\n", err)
				c.JSON(http.StatusBadRequest, EncryptedResponse{
					Success: false,
					Message: "Invalid request format",
				})
				c.Abort()
				return
			}

			fmt.Printf("📥 Received encrypted data: %s\n", encReq.Data[:50]+"...")

			// 解密数据
			decryptedData, err := crypto.Decrypt(encReq.Data)
			if err != nil {
				fmt.Printf("❌ Decryption error: %v\n", err)
				c.JSON(http.StatusBadRequest, EncryptedResponse{
					Success: false,
					Message: "Decryption failed",
				})
				c.Abort()
				return
			}

			fmt.Printf("🔓 Decrypted data: %s\n", decryptedData)

			// 将解密后的数据存储到上下文中
			c.Set("decryptedData", decryptedData)
		}
		c.Next()
	}
}

// 加密响应数据
func encryptResponse(data interface{}) EncryptedResponse {
	jsonData, err := json.Marshal(data)
	if err != nil {
		return EncryptedResponse{
			Success: false,
			Message: "Failed to marshal response",
		}
	}

	encryptedData, err := crypto.Encrypt(string(jsonData))
	if err != nil {
		return EncryptedResponse{
			Success: false,
			Message: "Encryption failed",
		}
	}

	return EncryptedResponse{
		Success: true,
		Data:    encryptedData,
		Message: "Success",
	}
}

// 处理用户登录
func handleLogin(c *gin.Context) {
	decryptedData, exists := c.Get("decryptedData")
	if !exists {
		c.JSON(http.StatusBadRequest, EncryptedResponse{
			Success: false,
			Message: "No decrypted data found",
		})
		return
	}

	var loginReq LoginRequest
	if err := json.Unmarshal([]byte(decryptedData.(string)), &loginReq); err != nil {
		c.JSON(http.StatusBadRequest, EncryptedResponse{
			Success: false,
			Message: "Invalid login data",
		})
		return
	}

	// 简单的登录验证逻辑
	if loginReq.Username == "admin" && loginReq.Password == "password123" {
		response := LoginResponse{
			Token:  "jwt-token-here",
			UserID: 1,
			Name:   "Admin User",
		}
		c.JSON(http.StatusOK, encryptResponse(response))
	} else {
		c.JSON(http.StatusUnauthorized, EncryptedResponse{
			Success: false,
			Message: "Invalid credentials",
		})
	}
}

// 获取用户信息
func getUser(c *gin.Context) {
	user := UserData{
		ID:    1,
		Name:  "John Doe",
		Email: "john@example.com",
		Age:   30,
		Phone: "+1234567890",
	}

	c.JSON(http.StatusOK, encryptResponse(user))
}

// 创建用户
func createUser(c *gin.Context) {
	decryptedData, exists := c.Get("decryptedData")
	if !exists {
		c.JSON(http.StatusBadRequest, EncryptedResponse{
			Success: false,
			Message: "No decrypted data found",
		})
		return
	}

	var user UserData
	if err := json.Unmarshal([]byte(decryptedData.(string)), &user); err != nil {
		c.JSON(http.StatusBadRequest, EncryptedResponse{
			Success: false,
			Message: "Invalid user data",
		})
		return
	}

	// 模拟创建用户
	user.ID = 123
	c.JSON(http.StatusCreated, encryptResponse(user))
}

// 获取用户列表
func getUsers(c *gin.Context) {
	users := []UserData{
		{ID: 1, Name: "John Doe", Email: "john@example.com", Age: 30, Phone: "+1234567890"},
		{ID: 2, Name: "Jane Smith", Email: "jane@example.com", Age: 25, Phone: "+0987654321"},
		{ID: 3, Name: "Bob Johnson", Email: "bob@example.com", Age: 35, Phone: "+1122334455"},
	}

	c.JSON(http.StatusOK, encryptResponse(users))
}

// 健康检查
func healthCheck(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status":  "OK",
		"message": "Server is running",
	})
}

func main() {
	// 初始化加密工具
	crypto = NewCryptoUtil(secretKey)

	// 创建Gin引擎
	r := gin.Default()

	// 配置CORS
	config := cors.DefaultConfig()
	config.AllowOrigins = []string{"*"}
	config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
	config.AllowHeaders = []string{"*"}
	r.Use(cors.New(config))

	// 公共路由（不需要加密）
	r.GET("/health", healthCheck)

	// 加密路由组
	api := r.Group("/api")
	api.Use(DecryptMiddleware())
	{
		api.POST("/login", handleLogin)
		api.POST("/users", createUser)
		api.GET("/users", getUsers)
		api.GET("/user", getUser)
	}

	// 启动服务器
	port := ":8080"
	fmt.Printf("Server starting on port %s\n", port)
	log.Fatal(r.Run(port))
}
